package com.stxx.stiot2.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.stxx.framwork.domain.R;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.stiot2.domain.SysUser;
import com.stxx.stiot2.service.SysUserService;
import org.noear.solon.annotation.*;

import java.sql.SQLException;
import java.util.Map;

@Controller
@Mapping("/sys-user")
public class SysUserController {

    @Inject
    SysUserService baseService;

    @Get
    @Mapping("/list")
    public PageResult<SysUser> list(SysUser bo, PageQuery pageQuery) throws SQLException {
        PageResult<SysUser> r = baseService.pageList(bo,pageQuery);
        return r;
    }
    
    @Post
    @Mapping("")
    public R<Object> add(@Body SysUser bo) throws SQLException {
        baseService.insert(bo);
        return R.ok("数据保存成功");
    }

    @Put
    @Mapping("")
    public R<Object> edit(@Body SysUser bo) throws SQLException {
        baseService.update(bo);
        return R.ok("数据保存成功");
    }

    @Delete
    @Mapping("/{ids}")
    public R<Object> remove(@Path Integer[] ids) throws SQLException {
        baseService.deleteByIds(ids);
        return R.ok("数据删除成功");
    }

    @Get
    @Mapping("/{userId}/reset-password")
    public R<Void> resetPassword(@Path Integer userId) throws SQLException {
        baseService.resetPassord(userId);
        return R.ok();
    }

    @Get
    @Mapping("/login-user")
    public R<SysUser> currUserInfo() throws SQLException {
        SysUser user = baseService.queryById(Integer.parseInt(StpUtil.getLoginId().toString()));
        return R.ok(user);
    }

    @Post
    @Mapping("/change-pwd")
    public R<Void> changePwd(@Body Map<String,String> params) throws SQLException {
        if(StrUtil.isEmpty(params.get("oldPassword"))){
            return R.fail("原始密码不能为空");
        }
        SysUser user = baseService.queryById(Integer.parseInt(StpUtil.getLoginId().toString()));
        if(!BCrypt.checkpw(params.get("oldPassword"),user.getPassword())){
            return R.fail("原始密码错误");
        }
        user.setPassword(params.get("password"));
        baseService.update(user);
        return R.ok();
    }
}
